﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.AspNetCore.Mvc;

namespace ApiData.Web.Filters
{
    public class AuthFilter : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var action = context.ActionDescriptor as ControllerActionDescriptor;
            var actionAttr = action.MethodInfo.GetCustomAttributes(true);
            var controllerAttr = action.MethodInfo.ReflectedType.GetCustomAttributes(true);

            if (actionAttr.Any(x => x is AllowAnonymousAttribute) || controllerAttr.Any(x => x is AllowAnonymousAttribute)) { }
            else
            {
                var str = context.HttpContext.Session.GetString("login-user");
                if (str.IsNullOrWhiteSpace())
                    RedirectOrAjax(context);
            }
        }

        public void RedirectOrAjax(AuthorizationFilterContext context)
        {
            if (IsAjax(context))
            {
                context.Result = new JsonResult(new Common.ResultData().Fail("未登录"));
            }
            else
            {
                context.Result = new RedirectResult("/Home/Index");
            }
        }

        public static bool IsAjax(FilterContext context)
        {
            bool result = false;
            var xreq = context.HttpContext.Request.Headers.ContainsKey("x-requested-with");
            if (xreq)
            {
                result = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
            }
            return result;
        }
    }
}
